import subprocess
import re
import sys
import argparse



def format_trace(output):
    try:
        block = re.search(b"write\(\d+,\s+\"(.*)\\\\n", output).group(1).replace(b"\\\\", b"\\")
        text = eval(b''.join([b'b"', block, b'".decode()']))
        sys.stdout.write(text+"\n")
        sys.stdout.flush()
    except:
        pass


def strace(pid, size=3000):
    cmd = ["strace", "-p", str(pid), "-ewrite", "-s", str(size)]
    process = subprocess.Popen(cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
    while process.poll() is None:
        output = process.stderr.readline(size)
        format_trace(output)




if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="查看进程输出")

    parser.add_argument("pid", help="进程PID", type=int)

    pid = parser.parse_args(sys.argv[1:]).pid
    strace(pid)
